package com.example.springboot1.limit;

import com.google.common.util.concurrent.*;
import org.springframework.lang.Nullable;

import java.util.UUID;
import java.util.concurrent.*;

/**
 * @author ckj
 * @description TODO
 * @date 2023-03-10 9:21
 */


public class MyThreadUtil {

    /**
     * 用户自定义线程池
     */
    private static ExecutorService executor = new ThreadPoolExecutor(10, 10,
            60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue(10));


    public static void doWork(Downloader downloader) {
        executor.submit(downloader);
    }


    /**
     * guava定义线程池
     */
    private static ListeningExecutorService pool = MoreExecutors.listeningDecorator(
            new ThreadPoolExecutor(5, 200,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(1024),
                    new ThreadFactoryBuilder()
                            .setNameFormat("download-pool-%d").build(),
                    new ThreadPoolExecutor.AbortPolicy())
    );

    private static ConcurrentHashMap<String, String> results = new ConcurrentHashMap<>();


    public static String run(Callable call) {
        ListenableFuture future = pool.submit(call);

        String id = UUID.randomUUID().toString();

        FutureCallback<String> callback = new FutureCallback<String>() {
            @Override
            public void onSuccess(@Nullable String s) {
                System.out.println("获取响应值" + s);
                results.put(id, s);
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        };
        Futures.addCallback(future, callback, pool);
        return id;
    }

    public static String getResult(String id) {
        return results.get(id);
    }


}
